package complex.java.threadlocal;

public class ThreadLocalTest2 {
	 private String threadName;  
	   
	    private ThreadLocal<String> threadNameLocal = new ThreadLocal<String>();  
	   
	    public String getThreadName() {  
	        return threadName;  
	    }  
	   
	    public void setThreadName(String threadName) {  
	        this.threadName = threadName;  
	    }  
	   
	    public String getThreadNameLocal() {  
	        return threadNameLocal.get();  
	    }  
	   
	    public void setThreadNameLocal(String nameLocal) {  
	        threadNameLocal.set(nameLocal);  
	    }  
	   
	    // 程序入口  
	    public static void main(String[] args) throws Exception {  
	        final ThreadLocalTest2 testObject = new ThreadLocalTest2();  
	   
	        // 启用三个线程同时操作 testObject  
	        for (int i = 0; i < 3; i++) {  
	            final int n = i;  
	   
	            new Thread() {  
	                private int id = n;  
	   
	                @Override  
	                public void run() {  
	                    try {  
	                        // 可以在输出中看到，每个线程在设置了 theadName 之后，再取出来时已经是一个不同的值；  
	                        // 而每个线程在设置了 theadNameLocal，再取出来还是原来的值。  
	   
	                        testObject.setThreadName(String.valueOf(this.hashCode()));  
	                        System.out.println("线程 " + id + " 设置 theadName 为 " + this.hashCode());  
	   
	                        testObject.setThreadNameLocal(String.valueOf(this.hashCode()));  
	                        System.out.println("线程 " + id + " 设置 theadNameLocal 为 " + this.hashCode());  
	   
	                        Thread.sleep(200);  
	   
	                        System.out.println("线程 " + id + " 获取 theadName 为 " + testObject.getThreadName());  
	                        System.out.println("线程 " + id + " 获取 theadNameLocal 为 " + testObject.getThreadNameLocal());  
	                    } catch (InterruptedException e) {  
	                        // nothing to do  
	                    }  
	                }  
	            }.start();  
	   
	            Thread.sleep(100);  
	        }  
	    }  
}
